﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Extensions.Options;
using System.Linq;
using Microsoft.EntityFrameworkCore;
using Stock.Model;
using Stock.Core.Common;
using Stock.Core.Service;
using Stock.Model.Entities;
using Stock.Model.ViewModels;

namespace Stock.Core.Services
{
    public class UserService : IUserService
    {
        private readonly XTContext _context;
        private readonly IUnitOfWork _u;
        private readonly IRepository<user> _users;

        public UserService(IUnitOfWork u)
        {
			_u = u;
			_context = _u.Context;
            _users = u.GetRepository<user>();
        }

        public async Task<bool> Addmoneny(Guid userid,  double moneny)
        {

			var user = await getUser(userid);
			user.balance += moneny;

            if(user.balance<=0)
            {
                return false;
            }

            await UpdateUser(user, false);

            var am =  _u.GetRepository<add_monenys>();
             am.Save(new add_monenys() { create_time = DateTime.Now, moneny = moneny, userid = userid }, false);

            return _u.Commit();
        }

        /// <summary>
        /// 查询充值记录
        /// </summary>
        /// <returns>The log.</returns>
        /// <param name="userid">Userid.</param>
        public async Task<List<add_monenys>> AddLog(Guid? userid, DateTime? start=null, DateTime? end=null)
        {
            var f = _u.GetRepository<add_monenys>();

            var query = from l in _context.add_monenys
                        orderby l.create_time descending
                        select l;

            if (end != null)
                query.Where(a => a.create_time <= end);

            if (start != null)
                query.Where(a => a.create_time >= start);

            if (userid != null)
                query.Where(a => a.userid == userid);

            return await query.ToListAsync();

        }

		public async Task<bool> ExsitOrderToday(Guid userid)
		{
            DateTime today = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day, 2, 0, 0);
            var q = from l in _u.Context.Set<order>()
                    where l.userid == userid && l.create_date > today
                                select l;

            return await q.CountAsync() > 0;
		}

        public async Task<BaseResult> Login(string username, string pwd)
        {

            var u = await _users.GetAsync(uitem => uitem.login_name == username);

            if (u != null && u.pwd == pwd)
            {
                if (u.balance < u.lessMoneny)
                {

                    if (!await ExsitOrderToday(u.id))
                        return new BaseResult() { Data = null, DataCount = 0, IsSuccess = false, Message = "帐户余额不足，请先开户" };
                    else
                        return new BaseResult() { Data = u.id, DataCount = 1, IsSuccess = true, Message = "" };
                }
                else
                    return new BaseResult() { Data = u.id, DataCount = 1, IsSuccess = true, Message = "" };
            }
            else
            {
                return new BaseResult() { Data = null, DataCount = 0, IsSuccess = false, Message = "用户名或密码错误" };

            }
        }

        public async Task<bool> ChangePwd(string username, string pwd, string newpwd)
        {
            var check = await this.Login(username, pwd);
            if(check.IsSuccess)
            {
                var u = await getUser(Guid.Parse(check.Data.ToString()));
                u.pwd = newpwd;
                return await UpdateUser(u, true);
            }
            return false;
        }

        public async Task<bool> SaveUser(user usr, bool tran)
		{
            var u = await _users.SaveAsync(usr, tran);


			return u;
		}

		public async Task<bool> UpdateUser(user usr, bool tran)
		{
            var u = await _users.UpdateAsync(usr, tran);


			return u;
		}

        public async Task<user> getUser(Guid userid)
        {
            var u = await _users.GetAsync(uitem => uitem.id == userid);


            return u;
        }

        public async Task<double> getBalance(Guid userid)
		{
            // 查余额
            var u = await getUser(userid);
            return u.balance;
		}


        public async Task<BaseResult> getCurrentFinance(Guid userid)
        {
            var u = await getUser(userid);

            var _order = new OrderService(_u);
            var orders =await _order.getCurrentOrders(userid);

            DateTime time = DateTime.Now;
            DateTime today = new DateTime(time.Year, time.Month, time.Day);
            long today_long = TimeHelper.ConvertDateTimeInt(today);

            long full = 0;
            long empty = 0;

            orders.ForEach(item=>
            {
                if (item.type == 1)
                    full += item.moneny;
                else if (item.type == 2)
                    empty += item.moneny;
            }
           );

            long yk =await _order.getOrderTotal(userid, today_long);

            return new BaseResult()
            {
                Data = new
                {
                    total = u.balance + u.freeze,
                    freeze = u.freeze,
                    full = full,
                    empty = empty,
                    yk = yk
                },
                DataCount = 1,
                IsSuccess = true,
                Message = ""
            };

        }

        public async Task<bool> CheckExsit(string username)
        {
            return await _users.IsExistAsync(u => u.login_name == username);
        }

        public async Task<bool> CheckExsitParent(string parentid)
		{
            return await _users.IsExistAsync(u => u.parentid == parentid);
		}

        public async Task<bool> Add(InsertUser iu)
        {
			user u = new user()
			{
                balance = iu.balance,
				freeze = iu.freeze,
                lessMoneny = iu.lessMoneny,
				login_name = iu.login_name,
				name = iu.name,
				pwd = iu.pwd,
                parentid = iu.parentid,
                type = iu.type,
			};


             await _users.SaveAsync(u, false);

            for (int i = 0; i < iu.sub_count; i++)
                {
                    user uu = new user()
                    {
                        balance = 0,
                        freeze = u.freeze,
                        lessMoneny = 0,
                        login_name = u.login_name + "_" + (i + 1).ToString(),
                        name = u.name,
                        parentid = u.id.ToString(),
                        pwd = u.pwd,
                        type = 2,
                    };
                await _users.SaveAsync(uu, false);
                }
            bool returnvalue = _u.Commit();
            return returnvalue;

        }

        public async Task<dynamic> GetList()
        {
            var query = from o in _context.Set<user>()
                                              where o.parentid == "0" || o.parentid == null
                                          select new { o.balance, o.lessMoneny, o.name,o.id };

			var data = await query.ToListAsync();

			return data;
        }
    }
}
